<template>
	<view class="bg"></view>
	<view class="" :style="{height: menuTopHeight + 'px'}"></view>
	<view class="menu-box" :style="{height: menuHeight + 'px'}">
		<u-icon name="arrow-left" color="#fff" size="20" @click="goBack"></u-icon>
		<view class="navigate-title">药品货庄</view>
	</view>
	<!-- 搜索 -->
	<view class="container">
		<view class="search-box">
			<u-search placeholder="搜索..." v-model="keyword" :showAction="false" @search="handleSearch"></u-search>
			<view class="" style="margin-left: 20rpx;">
				<u-image width="80rpx" height="80rpx" :src="getServerStatic('/static/images/a2.png')" @click="showPhone = true"></u-image>
			</view>
		</view>
		<!-- 轮播 -->
		<view class="swiper-box">
			<u-swiper height="262rpx" :list="swiperList"></u-swiper>
		</view>
		<!-- 金刚区 -->
		<view class="navigate-box">
			<u-grid :border="false" col="3" @click="navigateHandle">
				<u-grid-item v-for="(item, i) in navigateList" :key="i">
					<view class="item">
						<u-image radius="50%" width="110rpx" height="110rpx" :src="getServerStatic('/static/logo.png')" v-if="!item.icon"></u-image>
						<u-image radius="50%" width="110rpx" height="110rpx" :src="item.icon" v-else></u-image>
						<view class="name">{{item.name}}</view>
					</view>
				</u-grid-item>
			</u-grid>
		</view>
	</view>


	<!-- tab -->
	<view class="content-wrap">
		<view class="suggest-box">
			<view class="tabs">
				<u-tabs itemStyle="height: 100rpx;width: 50%;font-size: 30rpx;'" lineColor="#5780EF"
					activeStyle="color: #5780EF;" inactiveStyle="color: #606672;" :current="current" :list="tabsList"
					@click="tabsChange"></u-tabs>
			</view>
			<scroll-view scroll-x="true" class="suggest-scroll">
                <!--新品-->
				<view class="scroll-list" v-if="current == 0">
					<view class="commodity-item" v-for="(item, i) in newProducts" :key="i" @tap="goStoreDetail($event, item.id)">
						<view class="img-box">
							<u-image width="220rpx" height="200rpx" :src="checkAndFixUrl(item.cover)" mode="aspectFit"></u-image>
						</view>
						<view class="content-box">
							<view class="title">{{ item.name }}</view>
							<view class="price-box">
								<view class="price">￥{{ item.price }}</view>
								<view class="icon-box" @tap.stop="showPop($event,item)">
									<u-image width="44rpx" height="44rpx" :src="getServerStatic('/static/images/a63.png')"></u-image>
								</view>
							</view>
						</view>
					</view>
				</view>
                <!--热卖-->
                <view class="scroll-list" v-else>
                    <view class="commodity-item" v-for="(item, i) in hotSellProducts" :key="i" @tap="goStoreDetail($event, item.id)">
                        <view class="img-box">
                            <u-image width="220rpx" height="200rpx" :src="checkAndFixUrl(item.cover)" mode="aspectFit"></u-image>
                        </view>
                        <view class="content-box">
                            <view class="title">{{ item.name }}</view>
                            <view class="price-box">
                                <view class="price">￥{{ item.price }}</view>
                                <view class="icon-box" @tap.stop="showPop($event,item)">
                                    <u-image width="44rpx" height="44rpx" :src="getServerStatic('/static/images/a63.png')"></u-image>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
			</scroll-view>
		</view>

		<!-- 九宫格 -->
		<view class="grid-wrap" v-for="(label, index) in labelProducts" :key="index">
			<view class="title-box">
				<u-image width="34rpx" height="30rpx" :src="getServerStatic('/static/images/a64.png')"></u-image>
				<view class="title">{{ label.name }}</view>
				<u-image width="34rpx" height="30rpx" :src="getServerStatic('/static/images/a64.png')"></u-image>
			</view>
			<u-grid :border="false" col="3">
				<u-grid-item v-for="(item, i) in label.products" :key="i" @click="goStoreDetail($event, item.id)">
					<view class="commodity-item grid-bottom">
						<view class="img-box">
							<u-image width="220rpx" height="200rpx" :src="checkAndFixUrl(item.cover)" mode="aspectFit"></u-image>
						</view>
						<view class="content-box">
							<view class="title">{{ item.name }}</view>
							<view class="price-box">
								<view class="price">￥{{ item.price }}</view>
								<view class="icon-box" @tap.stop="showPop($event,item)">
									<u-image width="44rpx" height="44rpx" :src="getServerStatic('/static/images/a63.png')"></u-image>
								</view>
							</view>
						</view>
					</view>
				</u-grid-item>
			</u-grid>
		</view>


	</view>

	<!-- 购物车图标 -->
	<view class="car-icon-fixed" @tap="goStoreCar">
		<u-image width="110rpx" height="110rpx" :src="getServerStatic('/static/images/a65.png')"></u-image>
		<u-badge type="error" :offset="[0, 0]" :value="badge" absolute></u-badge>
	</view>

	<!-- 客服电话 -->
	<u-action-sheet round="30rpx" :show="showPhone" :actions="actions" title="" description="" @close="showPhone = false"
		@select="callConfirm">
	</u-action-sheet>

	<!-- 选择规格弹窗 -->
	<u-popup closeable bgColor="transparent" :show="skuPop" @close="skuPop = false">
		<view class="sku-pop">
			<view class="title">
				选择规格
			</view>
			<view class="content-box">
				<view class="left">
					<u-image width="170rpx" height="155rpx" v-if="selectSku && selectSku.pic && selectSku.pic !=='' " :src="checkAndFixUrl(selectSku.pic)"></u-image>
					<u-image width="170rpx" height="155rpx" v-else :src="checkAndFixUrl(productInfo.cover)"></u-image>
				</view>
				<view class="right">
					<view class="com-title">
						<text>￥</text>
						<text class="price" v-if="selectSku">{{ selectSku.price }}</text>
						<text class="price" v-else>{{ productInfo.price }}</text>
					</view>
					<view class="sku-box">购买数量：{{quantity}}件</view>
					<view class="count-box" v-if="selectSku">规格：{{ selectSku?.attr_name ?? '' }}</view>
				</view>
			</view>

			<view class="sku-select-box" v-for="(attr, index) in productAttrs" :key="index">
				<view class="sku-tip">{{ attr.name }}</view>
				<view class="sku-list">
					<view :class="['sku-item', isItemSelected(index , i) ? 'active' : '']" v-for="(item, i) in attr.values" :key="i" @tap="currentChange(index, i)">
                        {{ item }}
                    </view>
				</view>
			</view>


			<view class="sku-select-box pay-number">
				<view class="sku-tip">购买数量</view>
				<view class="sku-num">
					<u-number-box min="1" v-model="quantity"></u-number-box>
				</view>
			</view>
			<view class="confirm-btn">
				<u-button throttleTime="1000" :customStyle="{height: '80rpx'}" :hairline="false" type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @click="confirmPayment">确认</u-button>
			</view>
		</view>
	</u-popup>

    <!-- 选择规格弹窗组件 -->
    <SelectSku ref="selectSkuRef"
               :productAttrs="productAttrs"
               :productSkus="productSkus"
               :productInfo="productInfo"
               @confirmSku="confirmSku"
    >
    </SelectSku>

	<!-- 动画 -->
	<CartAnimation ref="cartAnimation"></CartAnimation>
</template>

<script setup>
    import {ref, reactive, readonly} from "vue"
    import {onLoad, onShow} from '@dcloudio/uni-app'
	import {useHeight} from '@/hooks/useMenuHeight'
	const {menuHeight, menuTopHeight} = useHeight()
    import {checkAndFixUrl, getServerStatic} from "@/utils/tool"
	import CartAnimation from '@/components/f-cartAnimation/f-cartAnimation'
    import SelectSku from '@/components/SelectSku'

    import {useSystemStore} from "@/store";
    import {getCategory, getHotSell, getLabels, getMallBanner, getNewProducts, getProductDetail} from "@/api/product";
    import {getCartsNumber, storeCart} from "@/api/cart";
    const systemStore = useSystemStore()

    const selectSkuRef = ref(null)

	onLoad((evt) => {
	    console.log('on load')

        handleGetBanner()
        handleGetHotSell()
        handleGetNewProducts()
        handleGetLabels()
	})

	onShow(() => {
	    console.log('on show')
	    handleGetHomeCategory()
        handleGetCartsNumber()
	})

    // 轮播图
    const swiperList = ref([])

    const handleGetBanner = async () => {
        const {code, data} = await getMallBanner({})
        if (code == 1) {
            swiperList.value = data.map(item => {
                return checkAndFixUrl(item?.image ?? '')
            })
        }
    }

    // 分类
    const navigateList = ref([])

    const handleGetHomeCategory = async () => {
        const {code, data} = await getCategory({parent_id: 0, is_show: 1})
        if (code == 1) {
            navigateList.value = data.map(item => {
                return {
                    ...item,
                    icon: checkAndFixUrl(item?.icon ?? '')
                }
            })
        }
        console.log(navigateList.value)
    }

    // tab切换
    const current = ref(0)
    const tabsList = ref([{
        name: '新品上新'
    },
        {
            name: '爆款热卖'
        }
    ])
    const tabsChange = e => {
        console.log(e)
        current.value = e.index
    }

    // 热卖
    const hotSellProducts = ref([])
    const handleGetHotSell = async () => {
        const {code, data} = await getHotSell({})
        if (code == 1) {
            hotSellProducts.value = data
        }
    }

    // 新品
    const newProducts = ref([])
    const handleGetNewProducts = async () => {
        const {code, data} = await getNewProducts({})
        if (code == 1) {
            newProducts.value = data
        }
    }

    // 标签商品
    const labelProducts = ref([])
    const handleGetLabels = async () => {
        const {code, data} = await getLabels({})
        if (code == 1) {
            labelProducts.value = data
        }
    }
    // 购物车商品数量
    const handleGetCartsNumber = async () => {
        const {code , data } = await getCartsNumber({})
        if (code === 1) {
            badge.value = data
        }
    }

	// 购物车动效 购物车数量
	const badge = ref(0)
	const cartAnimation = ref(null)
	const cartEvent = ref({})
	// 抛物线终点
	const busPos = {
		x: uni.getSystemInfoSync().windowWidth - 40,
		y: uni.getSystemInfoSync().windowHeight - 110
	}

	const confirmPayment = () => {
		skuPop.value = false
		cartAnimation.value.touchOnGoods(cartEvent.value, busPos)
		badge.value += 1
	}

    // 确认sku 加入购物车
    const confirmSku = async (result) => {
        console.log(result)
        console.log('选择的sku', result.sku.attr_name)

        // 加入购物车
        uni.showLoading({
            title: '加载中'
        });

        const {code, data, message} = await storeCart({sku_id: result.sku.id, quantity: result.quantity })
        uni.hideLoading();

        if (code === 1) {
            cartAnimation.value.touchOnGoods(cartEvent.value, busPos)
            badge.value = parseInt(badge.value) + parseInt(result.quantity)
        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }

    }

    // 购物车规格弹窗
    const skuPop = ref(false)
    // 选择的规格
    const skuCurrent = ref([]);

	// 规格切换
	const currentChange = (index, i) => {
        // 更新选中状态
        skuCurrent.value[index] = i;
        console.log('选中的规格', skuCurrent.value)

        let chooseSku = getMatchingSKU(skuCurrent.value)
        if (chooseSku) {
            selectSku.value = chooseSku
        }
	}
    // 是否选中
    const isItemSelected = (index, i) => {
        return skuCurrent.value[index] == i;
    }

    // 根据选择的属性值获取匹配的SKU
    const getMatchingSKU = () => {
        // 判断是否全部选择
        if (skuCurrent.value.length !== productAttrs.value.length) {
            return null;
        }

        // 构建匹配函数
        const matchingSKU = productSkus.value.find(sku => {
            return skuCurrent.value.every((value, index) => sku.variants[index] === value);
        });

        return matchingSKU || null;
    };

    // 商品属性
    const productAttrs = ref([])
    // 商品规格
    const productSkus = ref([])
    // 商品信息
    const productInfo = ref({})
    // 选择的规格
    const selectSku = ref(null)
    // 数量
    const quantity = ref(1)

    // 展示规格
	const showPop = async (event,item) => {
        console.log(event,item)

        // 获取商品详情
        uni.showLoading({
            title: '加载中'
        });

        const {code, data, message} = await getProductDetail({product_id: item.id})
        uni.hideLoading();

        if (code == 1) {
            console.log('商品', data)
            productInfo.value = data?.product ?? {}
            productAttrs.value = data?.product?.attrs ?? []
            productSkus.value = data?.product?.skus ?? []
            console.log('商品属性',productAttrs.value)
            console.log('商品SKU',productSkus.value)

            cartEvent.value = event
            selectSkuRef.value.open()

            return false;
            skuPop.value = true

        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }

	}

	// 分类跳转
	const navigateHandle = e => {
        console.log('分类ID', navigateList.value[e].id)
		uni.navigateTo({
			url: `/mine/drug-store/classification?category_id=${navigateList.value[e].id}`
		})
	}

    // 搜索参数
	const keyword = ref('')


    // 客服
    const showPhone = ref(false)
    const actions = ref([{
        name: `一键拨打：${systemStore.mallCustomerMobile}`,
        isCall: true
    },
        {
            name: '取消',
            isCall: false
        },
    ])
    // 拨打电话
    const callConfirm = e => {
        console.log(e);
        if (e.isCall) {
            uni.makePhoneCall({
                phoneNumber: systemStore.mallCustomerMobile
            })
        }
    }

    // 搜索
    const handleSearch = () => {
        console.log(keyword.value)
        uni.navigateTo({
            url: `/mine/drug-store/classification?keyword=${keyword.value}`
        })
    }
	// 商品详情
	const goStoreDetail = (e, productId) => {
        // console.log(e)
        // console.log(product)
        if (productId) {
            uni.navigateTo({
                url: `/mine/drug-store/detail?product_id=${productId}`
            })
        }
	}
	// 购物车
	const goStoreCar = () => {
		uni.navigateTo({
			url: '/mine/drug-store/car'
		})
	}
	// 返回
	const goBack = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.menu-box {
		padding-left: 26rpx;
		color: #fff;
		display: flex;
		align-items: center;
		.navigate-title {
			color: #fff;
			font-size: 36rpx;
			color: #FFFFFF;
			margin-left: 18rpx;
		}
	}
	.bg {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 483rpx;
		background: linear-gradient(180deg, #3165DE 0%, #3165DE 31%, rgba(255, 255, 255, 0.52) 100%);
		border-radius: 0rpx 0rpx 80rpx 80rpx;
		z-index: -1;
	}

	.container {
		padding: 28rpx 24rpx 0;
	}

	.search-box {
		display: flex;
		align-items: center;
	}

	.swiper-box {
		margin-top: 20rpx;
	}

	.navigate-box {
		margin-top: 30rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx 0 1rpx;
		// padding: 44rpx 10rpx 32rpx;
		.item {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;
			.name {
				font-size: 30rpx;
				color: #3B6CDF;
				margin-left: 12rpx;
			}
		}
	}

	.content-wrap {
		padding: 0 26rpx 80rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		.commodity-item {
			position: relative;
			width: 220rpx;
			// height: 330rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			margin-right: 20rpx;
			overflow: hidden;
			box-shadow: 0rpx 0rpx 10rpx 1rpx rgba(102,102,102,0.16);
			z-index: 99;
			.content-box {
				padding: 8rpx 8rpx 15rpx;
				.title {
					color: #666666;
					@include over-ellip();
					margin-bottom: 12rpx;
				}
				.price-box {
					@include between(100%);
					.price {
						font-size: 28rpx;
						color: #F55726;
					}
					.icon-box {
						@include center(44rpx, 44rpx);
						background: #516DDB;
						border-radius: 50%;
					}
				}
			}
		}
	}
	.suggest-box {
		position: relative;
		margin-top: 30rpx;
		.tabs {
			border-bottom: 1rpx solid #DFE5F6;
			margin-bottom: 30rpx;
			padding-bottom: 30rpx;
		}

		.suggest-scroll {
			white-space: nowrap;
			height: 330rpx;
			position: relative;
			width: 100%;
			display: flex;
			.scroll-list {
				display: flex;
				position: absolute;
				left: 0;
				top: 14rpx;

			}
		}
	}
	.grid-wrap {
		margin-top: 30rpx;
		padding-top: 34rpx;
		border-top: 1rpx solid #DFE5F6;
		.title-box {
			@include center();
			color: #516DDB;
			font-size: 36rpx;
			margin-bottom: 30rpx;
			.title {
				margin: 0 48rpx;
			}
		}
		.grid-bottom {
			margin-bottom: 30rpx;
		}
	}

	.car-icon-fixed {
		position: fixed;
		right: 26rpx;
		bottom: 210rpx;
		z-index: 999;
	}
	.sku-pop {
		background: #FFFFFF;
		border-radius: 30rpx 30rpx 0rpx 0rpx;
		padding: 40rpx 40rpx 52rpx;
		.title {
			font-size: 32rpx;
			color: #222222;
			text-align: center;
			margin-bottom: 50rpx;
		}
		.content-box {
			@include between(100%, 100%);
			margin-bottom: 70rpx;
			.right {
				flex: 1;
				margin-left: 22rpx;
				@include between(100%, 170rpx);
				flex-direction: column;
				align-items: flex-start;
				// padding: 10rpx 0;
				color: #000000;
				font-size: 30rpx;
				.com-title {
					color: #F55726;
					font-size: 28rpx;
					.price {
						font-weight: bold;
						font-size: 50rpx;
					}
				}
			}
		}
		.sku-select-box {
			margin-bottom: 40rpx;
			.sku-tip {
				color: #333333;
				font-size: 30rpx;
				margin-bottom: 30rpx;
			}
			.sku-list {
				@include start();
				flex-wrap: wrap;
				.sku-item {
					padding: 20rpx 26rpx;
					background: #EBEBEB;
					border-radius: 20rpx;
					color: #333333;
					font-size: 30rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					border: 1rpx solid #EBEBEB;
				}
				.active {
					background: #E8EBF6;
					border: 1rpx solid #516DDB;
				}
			}
		}
		.pay-number {
			margin-top: 50rpx;
			@include between(100%);
		}
		.confirm-btn {
			margin-top: 60rpx;
		}
	}
</style>
